/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    Image,
    DeviceEventEmitter,
    Text,
    View,
    Dimensions,
    TouchableOpacity,
}
    from
        'react-native';
import StyleUtils from "../res/styles/StyleUtils";
import CommonUtils, {getFormatDate} from "../common/CommonUtils";
import RegionsIcon from "../common/RegionsIcon";
import GoodsPage from "../pages/common/GoodsPage";
import I18n from "../res/language/i18n";
import IparImageView from "../custom/IparImageView";
import moment from 'moment';
import {DATE_DATA} from "../res/json/monthsJson";
import AlertDialog from "../custom/AlertDialog";
import IparNetwork, {SERVER_TYPE} from "../httpUtils/IparNetwork";
import LoginPage from "../pages/common/LoginPage";

const {width} = Dimensions.get('window');

export default class GoodsRender extends Component {

    constructor(props) {
        super(props);
        let size = this.props.goodsBoxSize ? this.props.goodsBoxSize : 2;
        this.regionsIcon = new RegionsIcon();
        this.commonUtils = new CommonUtils();
        this.iparNetwork = new IparNetwork();
        this.state = {
            goodsBoxWidth: (width / size) - 26,
            dataSource: this.props.dataSource,
            swap_amount: 0,
            currency_code: '',
            country: '',
            isPromote: true,
            userData: null,
            showAlert: false,
            alertVisible: false,
            promoteEntTime: '00:00:00',

        }
    }


    propTypes: {
        directBuy: PropTypes.bold,//是否直接购买
        directBuy: PropTypes.bold,//是否直接购买
        dataSource: PropTypes.request,//产品信息
        navigator: PropTypes.request,//跳页面到时候需要
    };

    componentDidMount() {
        this.upLoadData = DeviceEventEmitter.addListener('upLoadData', () => {
            this.onUpdate();
        });


        CommonUtils.getAcyncInfo('userInfo')
            .then((userData) => {
                this.setState({
                    userData: JSON.parse(userData)
                })
            });

        this.onUpdate();
        this.startPromoteTime(this.props.dataSource)
    }

    onUpdate() {
        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                if (result) {
                    let parse = JSON.parse(result);
                    this.setState({
                        country: parse.region_id,
                        swap_amount: parse.swap_amount,
                        currency_code: parse.currency_code,
                    })
                }
            });
    }

    componentWillUnmount() {
        this.upLoadData && this.upLoadData.remove();
    }

    /**
     * 条产品页面
     * @param selectGoodsData
     */
    startGoodsPage(selectGoodsData) {
        this.props.onPress && this.props.onPress(selectGoodsData);
        this.props.navigator && this.props.navigator.push({
            component: GoodsPage,
            name: 'GoodsPage',
            params: {
                countryImage: this.props.countryImage,
                goodsInfo: selectGoodsData
            }
        });
    }


    /**
     * props 该
     * */
    componentWillReceiveProps(nexProps) {

        if (this.state.dataSource != nexProps.dataSource) {
            this.startPromoteTime(nexProps.dataSource);
            this.setState({
                dataSource: nexProps.dataSource,
            });
        }

    }


    /**
     *倒计时
     **/
    startPromoteTime(data) {
        if (!data) return;
        if (!data.end_time) return;
        if (data.is_promote !== 1) return;
        if (!data.end_time) return;

        this.promoteTimer = setInterval(() => {
            const dateData = this.commonUtils.getDateData(data.end_time);

            if (dateData.days === 0 && dateData.hours === 0 && dateData.min === 0 && dateData.sec === 0) {
                this.setState({
                    isPromote: false,
                });
                this.promoteTimer && clearInterval(this.promoteTimer);
            } else {
                this.setState({
                    promoteEntTime: getFormatDate(dateData.days) + ' : '
                        + getFormatDate(dateData.hours) + ' : '
                        + getFormatDate(dateData.min) + ' : '
                        + getFormatDate(dateData.sec),
                })
            }
        }, 1000);
    }

    componentWillMount() {
        this.promoteTimer && clearInterval(this.promoteTimer);
    }


    getTitle(data) {

        let viewBoxTitle;

        let isPromote = false;
        if (data.is_promote === 1 && data.end_time) {
            isPromote = true;
            viewBoxTitle = {title: 'OFF', color: '#ff4e42'};
        } else if (data.is_new === 1) {
            viewBoxTitle = {title: 'NEW', color: '#ff9910'}
        } else if (data.is_hot === 1) {
            viewBoxTitle = {title: 'HOT', color: '#f34f4f'}
        } else if (data.is_best === 1) {
            viewBoxTitle = {title: 'SALE', color: '#97cd46'}
        }


        return (
            <View style={[StyleUtils.justifySpace, styles.goodsImageTitleBox]}>
                <View style={[StyleUtils.center, isPromote && {height: 22, backgroundColor: 'black', flex: 1}]}>
                    {isPromote && this.state.isPromote && <Text
                        style={{
                            color: 'white',
                            fontSize: 12,
                            borderRadius: 2,
                            paddingLeft: 4,
                            paddingRight: 4,
                        }}>{this.state.promoteEntTime}</Text>}
                </View>
                <Text
                    numberOfLines={1}
                    style={[styles.goodsImageTitle,
                        StyleUtils.smallFont,
                        viewBoxTitle && {backgroundColor: viewBoxTitle.color}]}>
                    {viewBoxTitle && viewBoxTitle.title}
                </Text>
            </View>)
    }

    render() {
        let data = this.state.dataSource;
        let userData = this.state.userData;
        let goodsCountryIcon = data && this.props.countryImage ? this.regionsIcon.getIcons(data.country) : null;

        let goodsName = '';
        if (data) {
            //goods name
            goodsName = data.goods_local_name;
            if (this.state.country === 'CN') {
                if (I18n.locale === 'uy') {
                    goodsName = data.goods_name;
                }
            } else {
                if (I18n.locale === 'en') {
                    goodsName = data.goods_name;
                }
            }
        }


        let renderRow = data ? (

            <TouchableOpacity
                onPress={() => this.startGoodsPage(data)}>

                {/**image box*/
                }
                <View style={[styles.imageBox, {
                    width: this.state.goodsBoxWidth,
                    alignItems: 'center',
                    height: this.state.goodsBoxWidth + 36,
                },]}>
                    {/**image title*/}
                    {this.getTitle(data)}
                    {/**goods image*/}

                    <IparImageView
                        width={this.state.goodsBoxWidth - 4}
                        height={this.state.goodsBoxWidth - 4}
                        url={data.image}/>

                    {/*soldOut*/}
                    {/*{data.num <= data.auto_off && <View style={[styles.soldOutStyle, StyleUtils.center]}>*/}
                    {/*    <Image*/}
                    {/*        style={{width: 30, height: 30}}*/}
                    {/*        source={require('../res/ic_sold_out.png')}/>*/}
                    {/*    <Text style={[{color: 'white'}, StyleUtils.smallFont]}>{I18n.t('o.soldOut')}</Text>*/}
                    {/*</View>}*/}
                </View>

                {/**报价*/
                }
                <View style={[this.props.goodsBoxSize ? null : StyleUtils.justifySpace, StyleUtils.marginTop]}>

                    <View style={[this.props.goodsBoxSize ? null : StyleUtils.rowDirection]}>
                        {data.is_promote === 1 && data.end_time ?
                            <Text style={[StyleUtils.goodsLineThroughText, StyleUtils.smallFont, {marginRight: 8}]}>
                                {(data.origin_pv * this.state.swap_amount).toFixed(0) + ' ' + this.state.currency_code}
                            </Text> : null}

                        <Text style={[StyleUtils.text, StyleUtils.smallFont, {
                            padding: 0,
                            color: 'black'
                        }]}>
                            {(data.goods_pv * this.state.swap_amount).toFixed(0) + ' ' + this.state.currency_code}
                        </Text>
                    </View>

                    {/*{this.props.directBuy && data.is_attr !== 1 && <TouchableOpacity*/}
                    {/*    onPress={() => {*/}
                    {/*        let userData = this.props.userData;*/}
                    {/*        if (userData) {*/}
                    {/*            this.setState({showAlert: true})*/}
                    {/*        } else {*/}
                    {/*            this.props.navigator.push({component: LoginPage, name: 'LoginPage'})*/}
                    {/*        }*/}
                    {/*    }}*/}
                    {/*    style={[{padding: 8}]}>*/}
                    {/*    <Image*/}
                    {/*        style={[{width: 18, height: 18, tintColor: 'black'}]}*/}
                    {/*        source={require('../res/images/tabIcons/ic_shop.png')}/>*/}
                    {/*</TouchableOpacity>}*/}
                </View>

                {/*{userData != null && userData.level > 0 &&*/}
                {/*<Text style={[StyleUtils.text, StyleUtils.smallFont, {padding: 0, color: 'black'}]}>*/}
                {/*    IBM {(data.shop_pv * this.state.swap_amount).toFixed(0) + ' ' + this.state.currency_code}*/}
                {/*</Text>}*/}
                {/**goods name*/
                }
                <Text
                    numberOfLines={2}
                    style={[StyleUtils.text, StyleUtils.smallFont, StyleUtils.marginTop, {
                        padding: 0,
                        color: '#333',
                        minHeight: 42,
                    }]}>
                    {goodsName}
                </Text>

                {/**country name*/
                }
                {
                    this.props.countryImage ?

                        <View style={[StyleUtils.rowDirection, {alignItems: 'center',}]}>
                            <Image
                                resizeMode="contain"
                                style={{height: 12, width: 20, resizeMode: 'contain'}}
                                source={goodsCountryIcon}/>
                            <Text
                                numberOfLines={1}
                                style={[styles.countryName, StyleUtils.smallFont]}>{this.goodsCountry(data.country)}</Text>
                        </View> : null
                }


                {/**加入购物车*/}
                <AlertDialog
                    contentTv={I18n.t('default.addedToCart')}
                    visible={this.state.showAlert}
                    leftBtnOnclick={() => this.buyGoods(true)}
                    rightBtnOnclick={() => this.buyGoods(false)}
                    leftSts={I18n.t('default.keepShopping')}
                    rightSts={I18n.t('default.payNow')}
                    requestClose={() => this.setState({showAlert: false})}/>


                <AlertDialog
                    requestClose={() => {
                        this.setState({
                            alertVisible: false,
                        });
                    }}
                    visible={this.state.alertVisible}
                    centerIcon={require('../res/ic_sold_out.png')}
                    contentTv={I18n.t('o.soldOut')}
                    centerSts={'ok'}
                    singleBtnOnclick={() => {
                        this.setState({
                            alertVisible: false,
                        })
                    }}/>
            </TouchableOpacity>
        ) : null;
        return (
            <View
                style={[{marginLeft: 16,}, StyleUtils.marginTop, StyleUtils.marginBottom, {width: this.state.goodsBoxWidth,},]}>
                {renderRow}
            </View>
        );
    }


    /***
     * 添加购物车
     * @param lop
     */
    buyGoods(lop) {
        this.setState({showAlert: false});
        const dataSource = this.state.dataSource;

        if (!dataSource) return;
        CommonUtils.showLoading();

        let userData = this.props.userData;
        let formData = new FormData();

        //isGlobal 的话 3
        let isGlobal = 2;
        if (dataSource.is_global === 1 && (dataSource.global_country && dataSource.global_country.indexOf(this.country) !== -1)) {
            isGlobal = 3;
        }

        formData.append('type', isGlobal);
        formData.append('country', dataSource.country);
        formData.append('product_id', dataSource.product_id);
        formData.append('goods_number', this.goodsNumber);
        formData.append('user_id', userData.user_id);
        formData.append('main_user_id', userData.main_user_id);
        formData.append('number_id', dataSource.number_id);
        formData.append('is_suite', dataSource.is_suite);
        formData.append('items', dataSource.items);


        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'addCart', formData)
            .then((result) => {
                let navigator = this.props.navigator;
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    DeviceEventEmitter.emit('isBuyGoods');
                    if (!lop) {
                        DeviceEventEmitter.emit('goToPage', 3);
                        navigator.popToTop();
                    }
                } else if (result.code === 504) {
                    this.setState({
                        alertVisible: true,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('GoodsRender--buyGoods-error: ', error)
            })
    }

    /*从xxx国家发货*/
    goodsCountry(name) {
        let goodsCountry;
        switch (name) {
            case 'RU':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Russia';
                break;
            case 'CN':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' China';
                break;
            case 'KZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kazakhstan';
                break;
            case 'US':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' United States';
                break;
            case 'KG':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kyrgyzstan';
                break;
            case 'AZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Azerbaijan';
                break;
            default:
                goodsCountry = name;
                break
        }
        return goodsCountry;
    }

}
const styles = StyleSheet.create({

    soldOutStyle: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        backgroundColor: 'rgba(0,0,0,0.32)'
    },

    countryName: {
        padding: 8,
        fontSize: 12,
        color: '#898b8d'
    },
    goodsImageTitle: {
        padding: 4,
        fontSize: 12,
        color: 'white'
    },
    goodsImageTitleBox: {
        width: '100%',
        marginBottom: 16,
// marginTop: 8,
    },

    imageBox: {
// padding: 20,
        paddingTop: 0,
        backgroundColor: '#f5f5f5'

    },
    goodsIcon: {
        backgroundColor: '#00aeff',
        width: '100%',
        height: '100%',
        resizeMode: 'contain',
    },
});
